package com.gxa.controller;

import com.gxa.advice.MyLog;
import com.gxa.config.SystemConfig;
import com.gxa.dto.ResultDto;
import com.gxa.exception.SystemException;
import com.gxa.groups.LoginByName;
import com.gxa.groups.LoginByPhone;
import com.gxa.mapper.AuthMapper;
import com.gxa.mapper.UserMapper;
import com.gxa.pojo.Auth;
import com.gxa.pojo.Menu;
import com.gxa.pojo.Role;
import com.gxa.pojo.User;
import com.gxa.service.LoginService;
import com.gxa.util.MD5Util;
import com.gxa.util.Response;
import com.gxa.util.SMSUtil;
import com.gxa.validate.MyValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/login")
public class LoginController {

    @Resource(name = "loginByPhoneService")
    private LoginService loginService;

    @Resource(name = "loginByNameService")
    private LoginService loginService2;

    @Autowired
    private AuthMapper authMapper;

    @Resource(type = SMSUtil.class)
    private SMSUtil smsUtil;

    @Autowired
    private MyValidator validator;

    @GetMapping("/byPhonePage")
    public String loginByPhonePage(){
        return "login";
    }

    @GetMapping("/byNamePage")
    public String loginByNamePage(){
        return "loginByName";
    }

    /**
     * 发送验证码
     * @param userPhone
     * @param session
     * @return
     */
    @PostMapping("/sendVerifyCode")
    @ResponseBody
    public ResultDto sendVerifyCode(String userPhone, HttpSession session){
        User user = new User();
        user.setUserPhone(userPhone);
        User checkUser = loginService.login(user);
        if (checkUser==null){
            throw new SystemException(1002, "该用户不存在！");
        }
        String code = smsUtil.getCode();
        if (!smsUtil.sendVerifyCode(userPhone, code)) {
            return Response.error(1001, "验证码发送失败");
        }
        session.setAttribute("verifyPhone", userPhone);
        session.setAttribute("verifyCode", code);
        return Response.success("发送成功！");
    }

    /**
     * 验证验证码是否正确
     * @param user
     * @param verifyCode
     * @param session
     * @return
     */
    @PostMapping("/checkVerifyCode")
    @ResponseBody
    public ResultDto checkVerifyCode(User user, String verifyCode, HttpSession session){
        String verifyCode1 = (String) session.getAttribute("verifyCode");
        String verifyPhone = (String) session.getAttribute("verifyPhone");
        if (!user.getUserPhone().toString().equals(verifyPhone)){
            throw new SystemException(1001, "该手机号尚未接收验证码");
        }
        if (!verifyCode.equals(verifyCode1)) {
            throw new SystemException(1002, "验证码不正确！~");
        }
        session.removeAttribute("verifyCode");
        session.removeAttribute("verifyPhone");
        return Response.success("验证成功!");
    }

    /**
     * 通过手机登录
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/byPhone")
    @ResponseBody
    @MyLog
    public ResultDto loginByPhone(User user, HttpSession session){
        validator.validate(user, LoginByPhone.class);
        User loginUser = loginService.login(user);
        if (loginUser==null){
            return Response.error(1003, "该用户不存在！");
        }
        loginUser.setUserUpdateTime(new Timestamp(System.currentTimeMillis()));
        loginService.updateLoginTime(loginUser);
        session.setAttribute("user", loginUser);

        User userDetail = loginService.findUserDetail(loginUser.getUserId());
        List<Menu> userMenuList = getUserMenuList(userDetail, session);
        session.setAttribute("userMenuList", userMenuList);

        return Response.success("登录成功！~");
    }

    /**
     * 通过用户名密码登录
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/byName")
    @ResponseBody
    @MyLog
    public ResultDto loginByName(User user, HttpSession session){
        validator.validate(user, LoginByName.class);
        User loginUser = loginService2.login(user);
        if (loginUser==null){
            return Response.error(1003, "该用户不存在！");
        }
        if (!loginUser.getUserPassword().equals(MD5Util.MD55(user.getUserPassword()))){
            return Response.error(1004, "密码错误！");
        }
        loginUser.setUserUpdateTime(new Timestamp(System.currentTimeMillis()));
        loginService2.updateLoginTime(loginUser);
        session.setAttribute("user", loginUser);

        User userDetail = loginService2.findUserDetail(loginUser.getUserId());
        List<Menu> userMenuList = getUserMenuList(userDetail, session);
        session.setAttribute("userMenuList", userMenuList);

        return Response.success("登录成功！~");
    }

    /**
     * 获取用户的菜单信息
     * @param user
     * @return
     */
    private List<Menu> getUserMenuList(User user, HttpSession session){
        List<Auth> authList;
        List<Menu> menuList;

        // 判断是否为超级管理员
        if (isSuper(user)){
            // 为超级管理员
            authList = authMapper.findAll();
            menuList = getMenuList(authList);
        }else {
            authList = new ArrayList<>();
            for (Role role : user.getRoleList()) {
                List<Auth> authList1 = role.getAuthList();
                authList.addAll(authList1);
            }
            menuList = getMenuList(authList);
        }
        session.setAttribute("isSuper", isSuper(user));
        session.setAttribute("authList", authList);
        return menuList;
    }

    /**
     * 判断是否为超级管理员
     * @param user
     * @return
     */
    private Boolean isSuper(User user){
        System.out.println(user);
        for (Role role : user.getRoleList()) {
            if (role == null || role.getIsSuper()==null){
                continue;
            }
            if (role.getIsSuper().equals(1)){
                return true;
            }
        }
        return false;
    }

    /**
     * 获取菜单列表
     * @param authList
     * @return
     */
    private List<Menu> getMenuList(List<Auth> authList){
        List<Menu> menuList = new ArrayList<>();
        for (Auth auth : authList) {
            if (auth.getIsMenu().equals(1) && auth.getAuthLevel().equals(1)){
                menuList.add(new Menu(auth.getAuthId(), auth.getAuthName(), auth.getAuthUrl(), 0, null));
            }
        }
        for (Menu menu : menuList) {
            List<Menu> subMenu = new ArrayList<>();
            for (Auth auth : authList) {
                if (auth.getAuthParentId().equals(menu.getMenuId()) && auth.getIsMenu().equals(1)){
                    subMenu.add(new Menu(auth.getAuthId(), auth.getAuthName(), auth.getAuthUrl(), menu.getMenuId(), null));
                }
            }
            menu.setMenuList(subMenu);
        }
        return menuList;
    }

}
